package cn.tedu.study.usermodel.controller;


import cn.tedu.study.response.ResultVO;
import cn.tedu.study.response.StatusCode;
import cn.tedu.study.security.CustomUserDetail;
import cn.tedu.study.usermodel.entity.dto.UserLoginDto;
import cn.tedu.study.usermodel.entity.dto.UserRegDto;
import cn.tedu.study.usermodel.entity.dto.UserUpdateDto;
import cn.tedu.study.usermodel.entity.pojo.User;
import cn.tedu.study.usermodel.entity.vo.UserVo;
import cn.tedu.study.usermodel.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author:yuziji
 * @create: 2023-06-06 20:40
 * @description:
 */
@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private AuthenticationManager manager;
    @Autowired
    private PasswordEncoder passwordEncoder;

    //    根据用户名查询
    @RequestMapping("/selectByUsername/{username}")
    public ResultVO selectByUsername(@PathVariable("username") String username) {
        UserVo userVo = userMapper.selectByUsername(username);
        if (userVo != null) {
            return new ResultVO(StatusCode.USERNAME_EXIST);
        }
        return ResultVO.ok();
    }

    //    注册方法
    @RequestMapping("/reg")
    public ResultVO reg(@RequestBody UserRegDto userRegDto) {
        User user = new User();
        BeanUtils.copyProperties(userRegDto, user);
        user.setCreateTime(new Date());
        user.setAvatar("/img/usermodel/mrtx.gif");
        user.setIsAdmin(0);
//        对密码进行加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userMapper.insert(user);
        return ResultVO.ok();
    }

    //    登录方法
    @RequestMapping("/login")
    public ResultVO login(@RequestBody UserLoginDto userLoginDto) {
//        通过认证管理器启动Security的认证流程
        Authentication result = manager.authenticate(new UsernamePasswordAuthenticationToken(userLoginDto.getUsername(),
                userLoginDto.getPassword()));
//        将认证结果保存到Security上下文中，让Security框架记住登录状态
        SecurityContextHolder.getContext().setAuthentication(result);
        return new ResultVO(StatusCode.SUCCESS, result.getPrincipal());
    }

    //    退出登录
    @RequestMapping("/logout/{id}")
    public void logout(@PathVariable("id") Integer id) {
        userMapper.updateLogoutStatus(id);
//        从security中删除认证数据
        SecurityContextHolder.clearContext();
    }

    @RequestMapping("/update")
    public ResultVO update(@RequestBody UserUpdateDto userUpdateDto, @AuthenticationPrincipal CustomUserDetail customUserDetail) {
        User user = new User();
        BeanUtils.copyProperties(userUpdateDto, user);
        userMapper.update(user);
        return ResultVO.ok();
    }

    @RequestMapping("/delete")
    public ResultVO delete(@AuthenticationPrincipal CustomUserDetail customUserDetail){
        userMapper.delete(customUserDetail.getId());
        return ResultVO.ok();
    }

}
